package businessLogic.service;

import dao.FactoryDAOFactory;
import dao.UserDAO;
import entity.User;
import java.util.ArrayList;
import java.util.List;
import vo.UserVO;

/**
 *
 * @author Zergio
 */
public class UserService<EntityManager> {

    private final int JPA = 1;
    private final int JDBC = 2;
    private UserDAO<EntityManager> userDao;

    public UserService(int id) {
        switch (id) {
            case JPA:
                userDao = FactoryDAOFactory.getInstance().getJPADaoFactory().getUserDAO();
                break;
            case JDBC:
                userDao = FactoryDAOFactory.getInstance().getJDBCDaofactory().getUserDAO();
                break;
        }
    }

    public void persist(UserVO vo, EntityManager em) {
        userDao.persist(toEntity(vo), em);
    }

    public UserVO find(Object id, EntityManager em) {
        User user = userDao.find(id, em);
        return user.toVO();
    }

    public void update(UserVO vo, EntityManager em) {
        userDao.update(toEntity(vo), em);
    }

    public void delete(Object id, EntityManager em) {
        userDao.delete((int)id, em);
    }

    public List<UserVO> getList(EntityManager em) {
        List<User> users = userDao.getList(em);
        List<UserVO> vos = new ArrayList<>();
        for (User user : users) {
            vos.add(user.toVO());
        }
        return vos;
    }

    public UserVO login(UserVO vo, EntityManager em) {
        User user = userDao.login(toEntity(vo), em);
        if (user != null) {
            return user.toVO();
        } else {
            return null;
        }
    }

    private User toEntity(UserVO vo) {
        User entity = new User();
        entity.setId(vo.getId());
        entity.setLogin(vo.getLogin());
        entity.setName(vo.getName());
        entity.setPasswd(vo.getPasswd());
        return entity;
    }
}
